package cn.com.czpb.client.module.version;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.custorm.AlertView;
import cn.com.czpb.client.model.version.VersionBean;
import cn.com.czpb.client.utils.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;

/**
 * Created by 猪猪侠 on 2017/7/14.
 */

public class VersionCheck {
    private Activity mActivity;
    private VersionBean mVersionBean;
    private  UpdateVersionListener mUpdateVersionListener;
    private int mLocalVersionCode;
    private LayoutInflater mLayoutInflater;
    private AlertView mAlertView;
    private AlertView mDownloadAlertView;
    private boolean mIsClickDownLoadButton;
    private String mFilePath;//文件保存路径
    private boolean mIsDownLoadSuccess;
    private boolean mIsDownLoadCancel;
    private ProgressBar mProgressBar;
    private TextView mDownloadPercentage;
    private TextView mDownloadSize;
    private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
    private MyTask myTask;

    public VersionCheck(Activity activity, VersionBean versionBean,UpdateVersionListener updateVersionListener){
        this.mActivity = activity;
        this.mVersionBean = versionBean;
        this.mFilePath = getLocalFilePath();
        this.mUpdateVersionListener = updateVersionListener;
        changeToUpdateInfo();//检测版本,设置,是否更新状态;
        mLayoutInflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    //检查是否需要更新
    private void changeToUpdateInfo(){
        if (mVersionBean!=null){
            mLocalVersionCode = getVersionCode();
            int serviceVersionCode = mVersionBean.VersionCode;
            mVersionBean.isNeedUpdate = mLocalVersionCode < serviceVersionCode;


        }
    }
    //开始更新
    public void beginCheckVersion(){
        if (mVersionBean==null){
            return;
        }
        if (mVersionBean.isNeedUpdate){
            showUpdateDialog();
        }else{

        }
        if (mUpdateVersionListener!=null){
            mUpdateVersionListener.onVersionChecked(mVersionBean.isNeedUpdate);
        }
    }
    private void showUpdateDialog(){
        if (mActivity==null||mActivity.isFinishing()){
            return;
        }
        mAlertView = new AlertView("今日海北", mVersionBean.updateMessage, "稍后再说", "立即升级", mActivity, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                LogUtils.i("position-->"+position);
                if (position!=AlertView.CANCELPOSITION){
                    mAlertView.dismiss();
                    showDownloadingDialog();
                    myTask = new MyTask();
                    myTask.execute(mVersionBean.downloadUrl);
//                    downloadApp(mVersionBean.downloadUrl, mFilePath);
                    mIsClickDownLoadButton = true;
                }else{
                    if (myTask!=null){
                        myTask.cancel(true);
                    }
                    mIsClickDownLoadButton = false;
                }
            }
        });
        mAlertView.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (mUpdateVersionListener != null) {
                    mUpdateVersionListener.onUpdateInfoDialogDismiss(mIsClickDownLoadButton);
                }
            }
        });
        mAlertView.setCancelable(false);
        mAlertView.show();
    }
    class MyTask extends AsyncTask<String,Integer,String>{

        public MyTask() {

        }
        @Override
        protected String doInBackground(String... params) {
            InputStream in = null;
            FileOutputStream out = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(false);
                urlConnection.setConnectTimeout(10 * 1000);
                urlConnection.setReadTimeout(10 * 1000);
                urlConnection.setRequestProperty("Connection", "Keep-Alive");
                urlConnection.setRequestProperty("Charset", "UTF-8");
                urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
                urlConnection.connect();
                long bytetotal = urlConnection.getContentLength();
                long bytesum = 0;
                int byteread = 0;
                in = urlConnection.getInputStream();
                File apkFile = new File(mFilePath);
                out = new FileOutputStream(apkFile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int oldProgress = 0;
                while ((byteread = in.read(buffer)) != -1) {
                    bytesum += byteread;
                    out.write(buffer, 0, byteread);

                    int progress = (int) (bytesum * 100L / bytetotal);
                    // 如果进度与之前进度相等，则不更新，如果更新太频繁，否则会造成界面卡顿
                    if (progress != oldProgress) {
                        publishProgress(Integer.valueOf(bytetotal+""),Integer.valueOf(bytesum+""));
                    }
                }
                if (!mIsDownLoadCancel){
                    installApk(apkFile);
                }
            } catch (Exception e) {
                mIsDownLoadSuccess = false;
                e.printStackTrace();
                LogUtils.e( "download apk file error");
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException ignored) {

                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ignored) {

                    }
                }
            }
            return "";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            mProgressBar.setMax(values[0]);//total
            mProgressBar.setProgress(values[1]);
            float current_f = values[1];
            float fileMax_f = values[0];
            NumberFormat percentFormat = NumberFormat.getPercentInstance(); // 得到百分比Format
            percentFormat.setMinimumFractionDigits(0);// 保留0位小数
            String percent_str = percentFormat.format(current_f / fileMax_f);
            mDownloadPercentage.setText(percent_str);
            float current_M = current_f / 1024 / 1024; // byte 转成 M
            float fileMax_M = fileMax_f / 1024 / 1024;
            NumberFormat numberFormat = NumberFormat.getNumberInstance(); // 得到数字Format
            numberFormat.setMaximumFractionDigits(1);// 保留1位小数
            String current_str = numberFormat.format(current_M);
            String fileMax_str = numberFormat.format(fileMax_M);
            if (current_str.length() == 1) {
                current_str = current_str + ".0";
            }
            mDownloadSize.setText(current_str + "M/" + fileMax_str + "M");
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    }

    // 安装apk
    private void installApk(File file) {
        mIsDownLoadSuccess = true;
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        mActivity.startActivity(intent);
        if (mUpdateVersionListener != null) {
            mUpdateVersionListener.onInstallAPK();
        }
    }


    private int getVersionCode(){
        try {
            // 获取PackageManager的实例
            PackageManager packageManager = mActivity.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(mActivity.getPackageName(), 0);
            return packInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    //获取本地保顿的 ,文件地址;
    private String getLocalFilePath() {
        File filePath = new File(mActivity.getExternalCacheDir(), "qilianshan_update.apk");
        if (filePath.exists()) {
            filePath.delete();
        }
        return filePath.getAbsolutePath();
    }

    /**
     * 显示下载对话框
     */
    private void showDownloadingDialog() {
        if (mActivity == null || mActivity.isFinishing()) {
            return;
        }
        View view = mLayoutInflater.inflate(R.layout.dialog_download, null, false);
        mDownloadAlertView = new AlertView("正在下载更新", null, "取消", null,mActivity, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == AlertView.CANCELPOSITION) {
                    mIsDownLoadCancel = true;
                    mIsDownLoadSuccess = false;
                }
            }
        });
        mDownloadAlertView.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (mUpdateVersionListener != null) {
                    mUpdateVersionListener.onDownLoadDialogDismiss(mIsDownLoadSuccess);
                }
            }
        });
        mProgressBar =  view.findViewById(R.id.download_progressbar);
        mDownloadPercentage = view.findViewById(R.id.download_percentage);
        mDownloadSize = view.findViewById(R.id.download_size);

        mDownloadAlertView.addExtView(view);
        mDownloadAlertView.setCancelable(false);
        LogUtils.i("showdialog-->2");
        mDownloadAlertView.show();
    }
}
